package com.yoo.chat.kit.conversation.messgelist.provider;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.LayoutDirection;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.text.TextUtilsCompat;
import io.rong.common.RLog;
import com.yoo.chat.kit.conversation.extension.component.emoticon.AndroidEmoji;
import com.yoo.chat.kit.model.State;
import com.yoo.chat.kit.model.UiMessage;
import com.yoo.chat.kit.utils.TextViewUtils;
import com.yoo.chat.kit.widget.adapter.IViewProviderListener;
import com.yoo.chat.kit.widget.adapter.ViewHolder;
import com.yoo.chat.kit.widget.refresh.util.DesignUtil;
import com.yoo.ons.R;

import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.TextMessage;
import java.util.List;
import java.util.Locale;

public class TextMessageItemProvider extends BaseMessageItemProvider<TextMessage> {

    public TextMessageItemProvider() {
        mConfig.showReadState = true;
    }

    @Override
    protected ViewHolder onCreateMessageContentViewHolder(ViewGroup parent, int viewType) {
        View view =
                LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.rc_translate_text_message_item, parent, false);
        return new ViewHolder(parent.getContext(), view);
    }

    @Override
    protected void bindMessageContentViewHolder(
            final ViewHolder holder,
            ViewHolder parentHolder,
            TextMessage message,
            final UiMessage uiMessage,
            int position,
            List<UiMessage> list,
            IViewProviderListener<UiMessage> listener) {
        final TextView textView = holder.getView(R.id.rc_text);
        final TextView translatedView = holder.getView(R.id.rc_translated_text);
        final ProgressBar progressBar = holder.getView(R.id.rc_pb_translating);

        if (!checkViewsValid(textView, translatedView, progressBar)) {
            RLog.e(TAG, "checkViewsValid error," + uiMessage.getObjectName());
            return;
        }

        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault())
                == LayoutDirection.RTL) {
            textView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END);
        }
        textView.setTag(uiMessage.getMessageId());
        if (uiMessage.getContentSpannable() == null) {
            SpannableStringBuilder spannable =
                    TextViewUtils.getSpannable(
                            message.getContent(),
                            new TextViewUtils.RegularCallBack() {
                                @Override
                                public void finish(SpannableStringBuilder spannable) {
                                    uiMessage.setContentSpannable(spannable);
                                    textView.post(
                                            new Runnable() {
                                                @Override
                                                public void run() {
                                                    if (TextUtils.equals(
                                                            textView.getTag() == null
                                                                    ? ""
                                                                    : textView.getTag().toString(),
                                                            String.valueOf(
                                                                    uiMessage.getMessageId())))
                                                        textView.setText(
                                                                uiMessage.getContentSpannable());
                                                }
                                            });
                                }
                            });
            uiMessage.setContentSpannable(spannable);
        }
        if (uiMessage.getMessage().getMessageDirection().getValue() == Message.MessageDirection.SEND.getValue()) {
            textView.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            textView.setTextColor(Color.parseColor("#000000"));
        }
        textView.setText(uiMessage.getContentSpannable());
        textView.setOnClickListener(
                view -> {
                    ViewParent parent = view.getParent();
                    if (parent instanceof View) {
                        ((View) parent).performClick();
                    }
                });

        textView.setOnLongClickListener(
                view -> {
                    ViewParent parent = view.getParent();
                    if (parent instanceof View) {
                        return ((View) parent).performLongClick();
                    }
                    return false;
                });

        boolean isSender =
                uiMessage.getMessage().getMessageDirection().equals(Message.MessageDirection.SEND);
        if (mConfig.showContentBubble) {
            textView.setBackgroundResource(isSender ? R.drawable.right_bg : R.drawable.left_bg);
        }

        if (uiMessage.getTranslateStatus() == State.SUCCESS
                && !TextUtils.isEmpty(uiMessage.getTranslatedContent())) {
            translatedView.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
            translatedView.setText(uiMessage.getTranslatedContent());
            holder.setBackgroundRes(
                    R.id.rc_translated_text,
                    isSender
                            ? com.yoo.module_res.R.drawable.rc_ic_translation_bubble_right
                            : com.yoo.module_res.R.drawable.rc_ic_translation_bubble_left);
        } else if (uiMessage.getTranslateStatus() == State.PROGRESS) {
            translatedView.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
            translatedView.setVisibility(View.GONE);
            holder.setBackgroundRes(
                    R.id.rc_pb_translating,
                    isSender
                            ? com.yoo.module_res.R.drawable.rc_ic_translation_bubble_right
                            : com.yoo.module_res.R.drawable.rc_ic_translation_bubble_left);
        } else {
            translatedView.setText(null);
            translatedView.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
            translatedView.setBackground(null);
        }

        setDirection(textView, isSender);
        setDirection(translatedView, isSender);
        setDirection(progressBar, isSender);

        holder.itemView.setOnClickListener(
                v -> {
                    ViewParent parent = v.getParent();
                    if (parent instanceof View) {
                        ((View) parent).performClick();
                    }
                });
        holder.itemView.setOnLongClickListener(
                v -> {
                    ViewParent parent = v.getParent();
                    if (parent instanceof View) {
                        return ((View) parent).performLongClick();
                    }
                    return false;
                });
    }


    private void setDirection(View view, boolean isSender) {
        ConstraintLayout.LayoutParams lp = ((ConstraintLayout.LayoutParams) view.getLayoutParams());
        if (isSender) {
            lp.startToStart = ConstraintLayout.LayoutParams.UNSET;
            lp.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
        } else {
            lp.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
            lp.endToEnd = ConstraintLayout.LayoutParams.UNSET;
        }
        view.setPadding(isSender?DesignUtil.dp2px(view.getContext(), 15f):DesignUtil.dp2px(view.getContext(), 19f), DesignUtil.dp2px(view.getContext(), 9f), isSender?DesignUtil.dp2px(view.getContext(), 19f):DesignUtil.dp2px(view.getContext(), 15f), DesignUtil.dp2px(view.getContext(), 9f));
        view.setLayoutParams(lp);
    }

    @Override
    protected boolean onItemClick(
            ViewHolder holder,
            TextMessage message,
            UiMessage uiMessage,
            int position,
            List<UiMessage> list,
            IViewProviderListener<UiMessage> listener) {
        return false;
    }

    @Override
    protected boolean isMessageViewType(MessageContent messageContent) {
        return messageContent instanceof TextMessage && !messageContent.isDestruct();
    }

    @Override
    public Spannable getSummarySpannable(Context context, TextMessage message) {
        if (message != null && !TextUtils.isEmpty(message.getContent())) {
            String content = message.getContent();
            content = content.replace("\n", " ");
            if (content.length() > 100) {
                content = content.substring(0, 100);
            }
            return new SpannableString(AndroidEmoji.ensure(content));
        } else {
            return new SpannableString("");
        }
    }

    @Override
    public boolean showBubble() {
        return false;
    }
}
